package com.qdu.mr.hbase;

import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.TableMapper;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;

import java.io.IOException;
import java.util.List;

public class CountHBaseMapper
        // 通过继承HBase封装过的父类，实现自动从HBase表读取数据
        // MapReduce与HBase集成时，表已经固定，所以数据也已经通过整行的方式提供给Mapper
        // 通过Result类型为当前map方法提供数据
        extends TableMapper<Text, LongWritable> {

    @Override
    protected void map(
            ImmutableBytesWritable key,
            Result value,  // 每一行数据通过Result提供
            Context context) throws IOException, InterruptedException {

        // 判断列是否存在
        if(value.containsColumn("f".getBytes(),"userid".getBytes())) {

            List<Cell> cellList = value.getColumnCells(
                    "f".getBytes(),
                    "userid".getBytes()
            );
            Cell cellvalue = cellList.get(0);
            String userid = new String(CellUtil.cloneValue(cellvalue));
            context.write(new Text(userid), new LongWritable(1));
        }
    }
}
